"use strict";

/**
 * @auther wtfssd
 * Created by wtfssd on 2017/11/2
 */
import * as React from 'react'
import {autoSize, commonStyles} from "../assets/styles/common";
import MyIcon from "./icon";
import {SCREEN_WIDTH} from "../constant";
import {MyGalleryProps} from "../interface/index";
import MyImagePicker from "./MyImagePicker";
import MyText from "./MyText";
import Colors from "../assets/styles/Colors";
import T from "../utils/T";


const {View, FlatList, TouchableOpacity, Image, CameraRoll, Alert, ActivityIndicator} = require('react-native');
const {connect} = require('react-redux');

class MyGallery extends React.Component<MyGalleryProps, any> {
    _itemSize: any;
    _images: Array<any>;


    _loadedPage: string[];
    static defaultProps = {
        onSelectedImage: null
    };

    constructor(props: any, context: any) {
        super(props, context);

        this.state = {
            images: null,
            loading: false,
            tip: T('loading') + '...',
            page_info: {
                start_cursor: null,
                end_cursor: null,
                has_next_page: false,
            }
        };
        this._loadedPage = [];
        this._itemSize = {width: SCREEN_WIDTH / 3, height: SCREEN_WIDTH / 3};

    }


    componentDidMount(): void {
        this.getPhotos({
            first: 8,
            assetType: 'Photos',
            groupTypes: 'All'
        }).then(({images, page_info}) => {
            this.setState({images: [1].concat(images), page_info});
        })
    }

    getPhotos = (params) => {
        return new Promise((resolve, reject) => {
            CameraRoll.getPhotos({
                ...params,

            }).then((data) => {
                resolve({images: data.edges, page_info: data.page_info});
            }).catch((e) => {
                this._images = [1];
                Alert.alert(
                    '当前暂无相册权限',
                    '无法获取相册信息，请前往设置->隐私->照片->火星空间 打开相册权限',
                    [
                        {text: '确定'},
                        {text: '取消'},
                    ]
                )
            });
        });
    };

    onEndReached = () => {
        if (!this.state.page_info || !this.state.page_info.has_next_page || this.state.loading) {
            return;
        }
        this.getPhotos({
            first: 9,
            assetType: 'Photos',
            groupTypes: 'All',
            after: this.state.page_info.end_cursor
        }).then(({images, page_info}) => {
            if (this._loadedPage.indexOf(page_info.end_cursor) === -1) {
                let image = this.state.images;
                this._loadedPage.push(page_info.end_cursor);
                if (page_info.has_next_page && page_info.end_cursor !== this.state.end_cursor) {
                    image = image.concat(images);
                    this.setState({
                        images: image,
                        page_info,
                        loading: false,
                        tip: page_info.has_next_page ? T('loading') + '...' : T('no more data') + '...'
                    })
                } else {
                    this.setState({
                        page_info: null,
                        tip: T('no more data')
                    })
                }
            } else {
                this.setState({
                    page_info: null,
                    loading: false,
                    tip: T('no more data')
                })
            }
        });
        this.setState({loading: true});
    };

    imageItemPress(image) {
        this.props.onSelectedImage && this.props.onSelectedImage(image)
    }

    cameraPress() {
        MyImagePicker.launchCamera({}, (res) => {
            if (res.error) {
                Alert.alert(
                    '当前暂无相机权限',
                    '无法获取相册信息，请前往设置->隐私->相机->火星空间 打开相机权限',
                    [
                        {text: '确定'},
                        {text: '取消'},
                    ]
                )
            } else {
                this.props.onSelectedImage && this.props.onSelectedImage({image: res})
            }
        });
    }


    renderItem = ({item, index}) => {
        if (index === 0) {
            return (
                <TouchableOpacity style={[commonStyles.centerVH, {...this._itemSize}]}
                                  activeOpacity={1} onPress={this.cameraPress.bind(this)}>
                    <MyIcon name='icon-icon-camera-copy' color='#DAC229' size={40}/>
                </TouchableOpacity>
            )
        }
        return (
            <TouchableOpacity style={[commonStyles.centerVH, {...this._itemSize}]}
                              activeOpacity={1}
                              onPress={this.imageItemPress.bind(this, item.node)}
            >
                <Image source={{uri: item.node.image.uri}}
                       style={{width: '100%', height: '100%'}}/>
            </TouchableOpacity>
        )
    };


    renderLoading = () => {
        return (
            <View style={[commonStyles.flex1, commonStyles.centerVH]}>
                <ActivityIndicator animated={!this.state.images || this.state.images.length <= 0}
                                   size={'small'}
                                   color={Colors.Active}/>
                <MyText color={Colors.Active}>{T('loading') + '...'}</MyText>
            </View>
        )
    };

    renderListFooterComponent = () => {
        return (
            <View style={[commonStyles.flexRow, commonStyles.centerVH, {width: SCREEN_WIDTH, height: autoSize(60)}]}>
                <ActivityIndicator animated={this.state.loading}
                                   hidesWhenStopped
                                   color={Colors.Active}
                                   size={'small'}/>
                <MyText style={{marginLeft: 10}}
                        color={Colors.Active}>{this.state.tip}{`共${this.state.images ? this.state.images.length : 0}张`}</MyText>
            </View>
        )
    };

    render() {


        let images = [];
        if (this.state.images) {
            this.state.images.map((i) => {
                if (images.indexOf(i) === -1) {
                    images.push(i);
                }
            });
        }
        return (
            <View {...this.props}>
                {this.state.images ? <FlatList data={images}
                                               extraData={this.state}
                                               style={{flex: 1}}
                                               numColumns={3}
                                               onEndReachedThreshold={1}
                                               onEndReached={this.onEndReached}
                                               ListFooterComponent={this.renderListFooterComponent}
                                               renderItem={this.renderItem.bind(this)}
                                               keyExtractor={(item, index) => index}
                /> : this.renderLoading()}
            </View>
        );
    }
}

export default MyGallery;